package Windows.Search;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JTabbedPane;
import javax.swing.tree.TreeNode;

import Client.msgSend;
import Tools.IMG;
import Tools.Log;
import Windows.MainWindows;
import Windows.ResToolBar;
import Windows.DownLoads.ShowDownloadPanel;
import Windows.Tree.TreeNodePic;
import XML.XMLNode;

/**
 * 搜索面板选择夹
 * 
 * @author Administrator
 * 
 */
public class SeachTabbedPane extends JTabbedPane {
	final TreeNodePic treeNode;
	private msgSend msgsend;
	ShowDownloadPanel sdp;
	ResToolBar rtb;
	private ArrayList<ResSearchTable> alrst = new ArrayList<ResSearchTable>();

	public SeachTabbedPane(ShowDownloadPanel sdp, ResToolBar rtb) {
		this.sdp = sdp;
		this.rtb = rtb;
		this.msgsend = MainWindows.getInstance().client;
		MainWindows.jToolBar1.jbCloseSearch.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (SeachTabbedPane.this.isShowing()) {// 确定组件正在显示
					CloseSearch();
				}
			}
		});

		treeNode = new TreeNodePic("搜索资源", IMG.SearchNode) {
			@Override
			public TreeNode getChildAt(int childIndex) {
				// 返回索引 childIndex 位置的子 TreeNode。
//				 System.out.println("SearchPane:getChildAt>>"+childIndex);
				return alrst.get(childIndex).getTreeNode();
			}

			@Override
			public int getChildCount() {
				// 返回接收者包含的子 TreeNode 数。
				return alrst.size();
			}

			@Override
			public int getIndex(TreeNode node) {
				// 返回接收者子节点中的 node 的索引。
				for (int i = 0; i < getChildCount(); i++) {
					if (alrst.get(i).getTreeNode().equals(node)) {
						return i;
					}
				}
				return -1;
			}
		};
	}

	/**
	 * 添加搜索任务
	 * 
	 * @param keys
	 */
	public void addSeach(XMLNode keys) {
		Log.print("[ADDSearch]" + keys);
//		keys.put("userid", MainWindows.getMainWindows().client.user);
		ResSearchTable rst = new ResSearchTable(keys, sdp, this, rtb);
		this.treeNode.add(rst.getTreeNode());
		rst.jmcls.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				CloseSearch();
			}
		});
		MainWindows.getInstance().client.addClientListenser(rst);
		this.add(keys.get("keys"), rst);
		MainWindows.Tree.jTree.setSelectionRow(1);
		this.setSelectedComponent(rst);
		alrst.add(rst);
		MainWindows.Tree.jTree.expandRow(1);// 展开节点
		MainWindows.Tree.jTree.updateUI();

	}

	/**
	 * 关闭当前搜索
	 */
	public void CloseSearch() {
		ResSearchTable rs = getSelectTable();
		if (rs != null) {
			MainWindows.getInstance().client.removeClientListenser(rs);
			this.treeNode.remove(rs.getTreeNode());
			this.remove(rs);
			alrst.remove(rs);
			MainWindows.Tree.jTree.updateUI();
		}
	}

	/**
	 * 获得当前搜索表格
	 * 
	 * @return
	 */
	public ResSearchTable getSelectTable() {
		return (ResSearchTable) getSelectedComponent();
	}

	public TreeNodePic getTreeNode() {
		return treeNode;
	}

}
